package com.christian.thread.safe;

import java.util.concurrent.TimeUnit;

/**
 * 文件描述：使用同步代码块解决线程安全问题
 *
 * @Author：wang
 * @Date：2020-01-20 10:15:10
 */
public class SolveGrabVotesSyncheoizedBlock {

    /**
     * 总票数
     */
    private static int totalVotes = 100;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (totalVotes > 0) {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //买票
                sale();
            }
        }, "窗口1");

        Thread t2 = new Thread(() -> {
            while (totalVotes > 0) {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //买票
                sale();
            }
        }, "窗口2");

        t1.start();
        t2.start();
    }

    /**
     * 买票
     */
    public static void sale() {
        synchronized (SolveGrabVotesSyncheoizedBlock.class) {
            if (totalVotes > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出第 " + (100 - totalVotes + 1) + " 张票");
                totalVotes--;
            }
        }
    }
}
